package com.ziyia.broacastbasepractivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {
    private ForceOffLineReceiver forceOffLineReceiver;
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.ziyia.broacastbasepractivity.FORCE_OFFLINE");
        forceOffLineReceiver = new ForceOffLineReceiver();
        registerReceiver(forceOffLineReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(forceOffLineReceiver);

    }

        @Override
        protected void onDestroy () {
            super.onDestroy();
            ActivityCollector.removeActivity(this);
        }

        class ForceOffLineReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Warning");
                builder.setMessage("You are forced to be offline. Please try to login again.");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCollector.finishAll();
                        Intent intent1 = new Intent(context, LoginActivity.class);
                        startActivity(intent1);
                    }
                });
                builder.setCancelable(false);
                builder.create();
                builder.show();
            }
        }
    }
